package com.czh.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.czh.domain.ResponseResult;
import com.czh.enums.AppHttpCodeEnum;
import com.czh.hander.exception.SystemException;
import com.czh.service.UploadService;
import com.czh.utils.PathUtils;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Service
@Data
@ConfigurationProperties(prefix = "aliyun.oss")
public class UploadServiceImpl implements UploadService {
    private String accessKey;
    private String secretKey;
    private String bucket;

    public ResponseResult<String> uploadImg(MultipartFile img) {
        //判断文件类型
        //获取原始文件名
        String originalFilename = img.getOriginalFilename();
        if (originalFilename == null || "".equals(originalFilename)) {
            throw new SystemException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //正则表达式判断文件类型
        if (!originalFilename.toLowerCase().matches(".*\\.(jpg|png|gif|jpeg)$")) {
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }
        //如果判断通过上传文件到OSS
        String filePath = PathUtils.generateFilePath(originalFilename);
        String url = uploadOss(img, filePath);//  2099/2/3/dsf.png
        return ResponseResult.okResult(url);
    }

    private String uploadOss(MultipartFile imgFile, String filePath) {
//        //构造一个带指定 Region 对象的配置类
//        Configuration cfg = new Configuration(Region.autoRegion());
//        //...其他参数参考类注释
//        UploadManager uploadManager = new UploadManager(cfg);
//        //默认不指定key的情况下，以文件内容的hash值作为文件名
//        try {
//            InputStream inputStream = imgFile.getInputStream();
//            Auth auth = Auth.create(accessKey, secretKey);
//            String upToken = auth.uploadToken(bucket);
//            try {
//                Response response = uploadManager.put(inputStream, filePath,upToken,null, null);
//                //解析上传成功的结果
//                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//                System.out.println(putRet.key);
//                System.out.println(putRet.hash);
//                return "http://sat2r54d9.hn-bkt.clouddn.com/"+ filePath;
//            } catch (QiniuException ex) {
//                Response r = ex.response;
//                System.err.println(r.toStrifing());
//                try {
//                    System.err.println(r.bodyString());
//                } catch (QiniuException ex2) {
//                    throw new SystemException(AppHttpCodeEnum.UPLOAD_ERROR);
//                }
//            }
//        } catch (Exception ex) {
//            throw new SystemException(AppHttpCodeEnum.UPLOAD_ERROR);
//        }
//        return "www";
//    }
        //阿里云oss
        String endpoint = "https://oss-cn-chengdu.aliyuncs.com";
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKey, secretKey);
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        try {
            ossClient.putObject(bucket, filePath, new ByteArrayInputStream(imgFile.getBytes()));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        String path= "https://czhblog.oss-cn-chengdu.aliyuncs.com/"+filePath;
        System.err.println(path);;
        return path;
    }
}
